//思路：平衡二叉树，利用后序遍历向上传递信息


import java.util.*;
class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }



 public class Solution {

     public boolean isBalanced(TreeNode root) {
         if(root==null) return true;
        return  treeheight(root)!=-1;

     }
     public  int treeheight(TreeNode r){
         if(r==null) return 0;
         int lheight=treeheight(r.left);
         if(lheight==-1) return -1;
         int rheight=treeheight(r.right);
         if(rheight==-1) return -1;
         if(Math.abs(lheight-rheight)>1) return -1;
         return Math.max(lheight,rheight)+1;
     }

}